<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Handlers\WeconHandler;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Cabinet extends Model
{
    protected $table = 'xfy_cabinets';
    protected $fillable = ['name', 'project_id', 'pid', 'box_id','group_id', 'record_type'];

    const RECORD_TYPE_API = 1;  //废弃
    const RECORD_TYPE_MQTT = 2; //废弃
    const RECORD_TYPE_TEXT = [self::RECORD_TYPE_API => '被动', self::RECORD_TYPE_MQTT => '主动'];   //废弃

    const SHOW_YES = 1;
    const SHOW_NO = 0;
    const SHOW_TEXT = ['0' => '隐藏', '1' => '显示'];

    const CACHE_KEY_ = 'yun_cabinet_data_';

    public function points()
    {
        return $this->hasMany(CabinetPoint::class, 'cabinet_id');
    }

    public static function syncWeikong($pid){
        $parentDevice = self::find($pid);
        $boxId = $parentDevice['box_id'];

        $groups = WeconHandler::getRealtimeGroups($boxId);
        if ($groups) {
            foreach ($groups as $oneGroup) {
                $m = self::where('box_id', $boxId)->where('group_id', $oneGroup['groupId'])->first();
                $points = WeconHandler::getConfigList($boxId, $oneGroup['groupId']);
                if (empty($points)) {
                    continue;
                }
                if (!$m) {
                    $cabinetData = [
                        'name' => $oneGroup['groupName'],
                        'project_id' => $parentDevice['project_id'],
                        'pid' => $pid,
                        'box_id' => $boxId,
                        'group_id' => $oneGroup['groupId'],
                    ];
                    $pointModels = [];
                    foreach ($points as $onePoint) {
                        $onePointData = [
                            'name' => $onePoint['monitorName'],
                            'alias' => 'a_'.$onePoint['monitorId']
                        ];
                        $pointModels[] = new CabinetPoint($onePointData);
                    }
                    $newCabinet = self::create($cabinetData);
                    $newCabinetPoints = $newCabinet->points()->saveMany($pointModels);
                } else {
                    $m->name = $oneGroup['groupName'];
                    $m->project_id = $parentDevice['project_id'];
                    $m->save();

                    foreach ($points as $onePoint) {
                        $searchArr = [
                            'cabinet_id' => $m['id'],
                            'alias' => 'a_'.$onePoint['monitorId'],
                        ];
                        $updateArr = [
                            'cabinet_id' => $m['id'],
                            'alias' => 'a_'.$onePoint['monitorId'],
                            'name' => $onePoint['monitorName'],
                        ];
                        CabinetPoint::updateOrCreate($searchArr, $updateArr);

                        $pointNamesArr['a_'.$onePoint['monitorId']] = $onePoint['monitorName'];
                    }
                    //清除维控平台被删除的监控点
                    $oldPoints = CabinetPoint::where('cabinet_id', $m['id'])->get();
                    foreach ($oldPoints as $oneOldPoints) {
                        if (!isset($pointNamesArr[$oneOldPoints['alias']])) {
                            $oneOldPoints->delete();
                        }
                    }
                }
                $groupNamesArr[$oneGroup['groupId']] = $oneGroup['groupName'];
            }
            //清除维控平台被删除的柜子
            $oldCabinets = self::where('box_id', $boxId)->where('group_id', '>', 0)->get();
            foreach ($oldCabinets as $oneOldCabinet) {
                if (!isset($groupNamesArr[$oneOldCabinet['group_id']])) {
                    $oneOldCabinet->points()->detach();
                    $oneOldCabinet->delete();
                }
            }
        }
    }

    public static function sendNotice(){
        $cabinets = self::select('id', 'box_id', 'group_id')->where('box_id', '>', 0)->where('group_id', '>', 0)->get()->toArray();
        if ($cabinets) {
            for ($i=0; $i < 3; $i++) {
                foreach ($cabinets as $oneCabinet) {
                    WeconHandler::sendNotice($oneCabinet['box_id']);
                }
                sleep(20);
            }
        }
    }

    public static function afterDeletedBox($pid, $wkBoxId){
        $cabinets = self::where('pid', $pid)->get();
        foreach ($cabinets as $one) {
            self::afterDeletedCabinet($one['id'], $one['box_id'], $one['group_id']);
            $one->delete();
        }
    }

    public static function afterDeletedCabinet($id, $wkBoxId, $wkGroupId){
        DB::table('xfy_cabinet_points')->where('cabinet_id', $id)->delete();
        DB::table('xfy_cabinet_alarms')->where('cabinet_id', $id)->delete();
        DB::table('xfy_cabinet_alarm_logs')->where('cabinet_id', $id)->delete();
        DB::table('xfy_cabinet_data')->where('cabinet_id', $id)->delete();
    }

    public function box()
    {
        return $this->belongsTo(Cabinet::class, 'pid');
    }
}